import Vue from "vue";
import NetworkUtil from "@/utils/NetworkUtil";
import "./routerUtils";
import UrlNS from "@/api/UrlDefine";
import store from "@/store";
import { UserStoreModule } from "@/store/modules/UserStore";

Vue.prototype.$isMobile = navigator.userAgent.match(
  /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
);
Vue.prototype.$isAndroid =
  navigator.userAgent.indexOf("Android") > -1 ||
  navigator.userAgent.indexOf("Adr") > -1;

Vue.prototype.$successMsg = (message: string) => {
  Vue.prototype.$message({
    message,
    type: "success",
    duration: 5000,
  });
};
Vue.prototype.$errorMsg = (message: string) => {
  Vue.prototype.$message({
    message,
    type: "error",
    duration: 5000,
  });
};

Vue.prototype.$showConfirmDialog = (message: string): Promise<void> => {
  return Vue.prototype.$confirm(message, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
};

Vue.prototype.publishEvent = function (eventName: string, payload: any) {
  if (!eventName) return;
  const fun = this[eventName];
  fun && fun(payload);
};

Vue.prototype.registeEvent = function (events: any) {
  for (const item in events) {
    const handle = events[item];
    if (handle instanceof Function) {
      this[item] = handle.bind(this);
    }
  }
};

Vue.prototype.isInited = function (prop: string) {
  return this[prop] && this[prop].init;
};

Vue.prototype.$post = <T>(
  url: string,
  params: any,
  header?: any
): Promise<T> => {
  const promise = new Promise<T>((resolve, reject) => {
    NetworkUtil.postReqByHeads<T>(url, header || {}, params)
      .then((res) => {
        //
        console.log(res);
        if (res.status === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      })
      .catch((err: Error) => {
        //
        console.error("err", JSON.stringify(err));
        reject(err.message);
      });
  });
  return promise;
};
